import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { utilsSecret } from '../utils/index';
import { JWT_SECRET } from "../constant"

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), // 指定从请求头中提取 JWT 的方式。
      ignoreExpiration: false, // 是否忽略 token 的过期时间。
      // secretOrKey: utilsSecret.Secret.getInit().generateSecretKey(), // Use the same secret key
      // secretOrKey: JWT_SECRET,
      secretOrKey: '3a7934ed56223528bb31eeb616394ac6c55bfb2acb63eafe7f6b1868ecd753ac'
    });
  }

  // 用于验证 JWT 的有效负载。
  async validate(payload: any) {
    // Here you can add additional validation logic if needed
    if (!payload) {
      throw new UnauthorizedException();
    }
    // return { userId: payload.sub, username: payload.username };
    // return payload;
    return { userId: payload.sub, username: payload.username, roles: payload.roles };
  }
}